package com.ccy.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.ccy.search.config.GuliEsSearchConfig;
import com.ccy.search.service.SearchEsModelService;
import com.ccy.search.to.SkuEsModel;
import com.ccy.search.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author coder_ccy
 * @date 2022/7/21 9:01
 */
@Service
public class SearchEsModelServiceImpl implements SearchEsModelService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Override
    public void up(List<SkuEsModel> skuEsModels) throws IOException {
        //1. 构建bulkRequest
        BulkRequest bulkRequest = new BulkRequest("product");

        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);


            bulkRequest.add(indexRequest);
        }


        //2. 执行批量添加
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, GuliEsSearchConfig.COMMON_OPTIONS);


        //3. 解析res
        boolean b = bulkResponse.hasFailures();
        if(b){
            List<String> failureIds = Arrays.stream(bulkResponse.getItems()).map(o -> {
                return o.getId();
            }).collect(Collectors.toList());

        }
    }

    @Override
    public SearchResult search(SearchParam searchParam) throws IOException {

        //测试数据
        searchParam = new SearchParam();
        searchParam.setKeyword("华为");
        searchParam.setBrandId(Arrays.asList(2l,4l));
        searchParam.setSkuPrice("10_20000");


        //1. 构建searchRequest
        SearchRequest searchRequest = builderSearchRequest(searchParam);

        //2. 执行查询
        SearchResponse response = restHighLevelClient.search(searchRequest, GuliEsSearchConfig.COMMON_OPTIONS);

        //3. 解析结果

        SearchResult result = analizeResponse(response,searchParam);
        return result;
    }


    private SearchResult analizeResponse(SearchResponse response,SearchParam param){

        SearchResult result = new SearchResult();

        SearchHits hits = response.getHits();
        //1. 封装查询到的商品信息
        if (hits.getHits()!=null&&hits.getHits().length>0){
            List<SkuEsModel> skuEsModels = new ArrayList<>();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //设置高亮属性  isEmpty  isBlank   "    jack   "  "    "   trim()
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highLight = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(highLight);
                }
                skuEsModels.add(skuEsModel);
            }
            result.setProducts(skuEsModels);
        }



        //2. 封装分页信息
        //2.1 当前页码
        result.setPageNum(param.getPageNum());
        //2.2 总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //2.3 总页码
        Integer totalPages = (int)total % param.getPageSize()== 0 ?
                (int)total / param.getPageSize() : (int)total / param.getPageSize() + 1;
        result.setTotalPages(totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //3. 查询结果涉及到的品牌
        Aggregations aggregations = response.getAggregations();
        List<BrandVo> brandVos = new ArrayList<>();
        //ParsedLongTerms用于接收terms聚合的结果，并且可以把key转化为Long类型的数据
        ParsedLongTerms brandAgg = aggregations.get("brandIdAgg");
        if (null != brandAgg){
            for (Terms.Bucket bucket : brandAgg.getBuckets()) {
                //3.1 得到品牌id
                Long brandId = bucket.getKeyAsNumber().longValue();

                Aggregations subBrandAggs = bucket.getAggregations();
                //3.2 得到品牌图片
                // ParsedStringTerms brandImgAgg=subBrandAggs.get("brandImgAgg");
                // String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
                //3.3 得到品牌名字
                Terms brandNameAgg = subBrandAggs.get("brandNameAgg");
                String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
                BrandVo brandVo = new BrandVo(brandId, brandName, null);
                brandVos.add(brandVo);
            }
        }
        result.setBrands(brandVos);

        //4. 查询涉及到的所有分类
        List<CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = aggregations.get("catalogIdAgg");
        if (null != catalogAgg){
            for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
                //4.1 获取分类id
                Long catalogId = bucket.getKeyAsNumber().longValue();
                Aggregations subcatalogAggs = bucket.getAggregations();
                //4.2 获取分类名
                ParsedStringTerms catalogNameAgg = subcatalogAggs.get("catalogNameAgg");
                String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
                CatalogVo catalogVo = new CatalogVo(catalogId, catalogName);
                catalogVos.add(catalogVo);
            }
        }
        result.setCatalogs(catalogVos);

        //5 查询涉及到的所有属性
        List<AttrVo> attrVos = new ArrayList<>();
        //ParsedNested用于接收内置属性的聚合
        ParsedNested parsedNested = aggregations.get("attrs");
        if (null != parsedNested){
            ParsedLongTerms attrIdAgg=parsedNested.getAggregations().get("attrIdAgg");
            for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
                //5.1 查询属性id
                Long attrId = bucket.getKeyAsNumber().longValue();

                Aggregations subAttrAgg = bucket.getAggregations();
                //5.2 查询属性名
                ParsedStringTerms attrNameAgg=subAttrAgg.get("attrNameAgg");
                String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
                //5.3 查询属性值
                ParsedStringTerms attrValueAgg = subAttrAgg.get("attrValueAgg");
                List<String> attrValues = new ArrayList<>();
                for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                    String attrValue = attrValueAggBucket.getKeyAsString();
                    attrValues.add(attrValue);
                    List<NavVo> navVos = new ArrayList<>();
                }
                AttrVo attrVo = new AttrVo(attrId, attrName, attrValues);
                attrVos.add(attrVo);
            }
        }
        result.setAttrs(attrVos);

        // 6. 构建面包屑导航
//        List<String> attrs = param.getAttrs();
//        if (attrs != null && attrs.size() > 0) {
//            List<NavVo> navVos = attrs.stream().map(attr -> {
//                String[] split = attr.split("_");
//                NavVo navVo = new NavVo();
//                //6.1 设置属性值
//                navVo.setNavValue(split[1]);
//                //6.2 查询并设置属性名
//                try {
//                    R r = productFeignService.info(Long.parseLong(split[0]));
//                    if (r.getCode() == 0) {
//                        AttrResponseVo attrResponseVo = JSON.parseObject(JSON.toJSONString(r.get("attr")), new TypeReference<AttrResponseVo>() {
//                        });
//                        navVo.setNavName(attrResponseVo.getAttrName());
//                    }
//                } catch (Exception e) {
//                    log.error("远程调用商品服务查询属性失败", e);
//                }
//                //6.3 设置面包屑跳转链接
//                String queryString = param.get_queryString();
//                String replace = queryString.replace("&attrs=" + attr, "").replace("attrs=" + attr+"&", "").replace("attrs=" + attr, "");
//                navVo.setLink("http://search.gulimall.com/search.html" + (replace.isEmpty()?"":"?"+replace));
//                return navVo;
//            }).collect(Collectors.toList());
//            result.setNavs(navVos);
//        }
        return result;
    }


    private SearchRequest builderSearchRequest(SearchParam searchParam){

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //1. 构建searchSourceBuilder


        //1.1 query


        //1.1.1 must
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle","华为"));


        //1.1.2. filter
        BoolQueryBuilder subBoolQueryBuilder = QueryBuilders.boolQuery();
        subBoolQueryBuilder.must(QueryBuilders.termQuery("hasStock","false"));


        RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("skuPrice");
        rangeQueryBuilder.gte(10);
        rangeQueryBuilder.lte(20000);
        subBoolQueryBuilder.must(rangeQueryBuilder);
        int[] brandIds = {2, 3, 4};

        subBoolQueryBuilder.must(QueryBuilders.termsQuery("brandId",brandIds));

        BoolQueryBuilder boolQueryBuilder1 = QueryBuilders.boolQuery();
        NestedQueryBuilder nestedQueryBuilder = new NestedQueryBuilder("attrs",boolQueryBuilder1, ScoreMode.None);
        boolQueryBuilder1.must(QueryBuilders.termQuery("attrs.attrId",1));
        boolQueryBuilder1.must(QueryBuilders.termsQuery("attrs.attrValue","4G","5G"));

        System.out.println("4g".equalsIgnoreCase("4G"));
        subBoolQueryBuilder.must(nestedQueryBuilder);
        boolQueryBuilder.filter(subBoolQueryBuilder);

        searchSourceBuilder.query(boolQueryBuilder);


        // isEmpty  isBlank  区别     “     ”
        //1.2 sort
        if(StringUtils.isNotEmpty(searchParam.getSort())  && searchParam.getSort().indexOf("_")>0){

        }
        //searchSourceBuilder.sort("saleCount", SortOrder.DESC);

        //1.3 from
        searchSourceBuilder.from(0);

        //1.4 size
        searchSourceBuilder.size(20);


        //1.5
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("skuTitle");
        highlightBuilder.preTags("<span style='color:skyblue'>");
        highlightBuilder.postTags("</span>");

        //1.6 aggs

        //1.6.1brandIdAgg

        TermsAggregationBuilder brandIdAgg = AggregationBuilders.terms("brandIdAgg").field("brandId");
        TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brandNameAgg").field("brandName");

        brandIdAgg.subAggregation(brandNameAgg);


        //1.6.2 catalogIdAgg

        TermsAggregationBuilder catalogIdAgg = AggregationBuilders.terms("catalogIdAgg").field("catalogId");
        TermsAggregationBuilder catalogNameAgg = AggregationBuilders.terms("catalogNameAgg").field("catalogName");

        catalogIdAgg.subAggregation(catalogNameAgg);

        //1.6.3 attrs
        // Arrays   Collections
        NestedAggregationBuilder nestedAggregationBuilder = new NestedAggregationBuilder("attrs","attrs");


        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attrNameAgg").field("attrs.attrName");
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue");

        nestedAggregationBuilder.subAggregation(attrIdAgg);
        attrIdAgg.subAggregation(attrNameAgg);
        attrIdAgg.subAggregation(attrValueAgg);

        searchSourceBuilder.aggregation(brandIdAgg);
        searchSourceBuilder.aggregation(catalogIdAgg);
        searchSourceBuilder.aggregation(nestedAggregationBuilder);

        searchSourceBuilder.highlighter(highlightBuilder);

        //2. 构建searchRequest
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("product");
        searchRequest.source(searchSourceBuilder);


        return searchRequest;


    }
}
